'use strict'

const {Blogs,Op} = require('../model');

let fn_blog_list =async (ctx,next)=>{
    let keyword = ctx.request.body.keyword;
    if (keyword) {
        let list = await Blogs.findAll({
            where:{
                [Op.or]:[
                    {id:isNaN(keyword) ? 0 : parseInt(keyword)},
                    {title:keyword},
                    {digest:keyword},
                    {content:keyword},
                    {classify:keyword},
                    {autor:keyword},
                    {time:keyword},
                ]
            }
        });
        ctx.body=list;
    }else{
        let list = await Blogs.findAll({
            order:['id']
        })
        ctx.body=list;
    }
}

let fn_blog_id =async (ctx,next)=>{
    let id = ctx.request.params.id;

    await Blogs.findByPk(id).then((res)=>{
        ctx.body=res;
    })
}

let fn_post =async (ctx,next)=>{
    let obj = ctx.request.body;

    await Blogs.create(obj);

    ctx.body='blog'
}

let fn_put =async (ctx,next)=>{
    let obj = ctx.request.body;

    await Blogs.findByPk(obj.id).then(async (res)=>{
        await res.update({
            id:obj.id,
            title:obj.title,
            digest:obj.digest,
            content:obj.content,
            classify:obj.classify,
            autor:obj.autor
        })
    })

    ctx.body='blog'
}

let fn_delete =async (ctx,next)=>{
    let id = ctx.request.params.id;

    await Blogs.destroy({
        where:{
            id:id
        }
    })

    ctx.body='blog'
}

module.exports={
    'get /blog':fn_blog_list,
    'get /blog/:id':fn_blog_id,
    'post /blog':fn_post,
    'put /blog':fn_put,
    'delete /blog/:id':fn_delete
}